import { createSlice } from '@reduxjs/toolkit'
import { getHotAlbums, getTopAlbums } from '../service/album'
import type { HotAlbumsType, TopAlbumsType } from './type'
import { createAsyncThunk } from '@reduxjs/toolkit'

export const fetchHotAlbumsAction = createAsyncThunk(
  'getHotAlbums',
  async (arg, { dispatch }) => {
    getHotAlbums().then((res) => {
      console.log(res)
      dispatch(changeHotAlbumsAction(res.albums))
    })
  }
)
export const fetchTopAlbumsAction = createAsyncThunk(
  'getTopAlbums',
  async (arg: { limit: number; offset: number }, { dispatch }) => {
    getTopAlbums(arg.limit, arg.offset).then((res) => {
      dispatch(changeTotalAction(res.total))
      console.log(res)
      dispatch(changeTopAlbumsAction(res.albums))
    })
  }
)


export interface AlbumState {
  hotAlbums: HotAlbumsType[]
  topAlbums: TopAlbumsType[]
  total:number
}

const initialState: AlbumState = {
  hotAlbums: [],
  topAlbums: [],
  total:0
}

export const albumList = createSlice({
  name: 'albumList',
  initialState,
  reducers: {
    changeHotAlbumsAction(state, action) {
      state.hotAlbums = action.payload
    },
    changeTopAlbumsAction(state, action) {
      state.topAlbums = action.payload
    },
    changeTotalAction(state, action) {
      state.total = action.payload
      // console.log(state.total)
    },


  }
})
export default albumList.reducer
export const { changeHotAlbumsAction, changeTopAlbumsAction,changeTotalAction } = albumList.actions
